package server

import (
    "context"
    "fmt"
    "github.com/spf13/cast"
    global2 "longmen/server/config/global"
    "longmen/server/pkg/common/helper/util"
    "longmen/server/pkg/db/mysql/db_live"
    "longmen/server/pkg/db/mysql/db_sports"
    db_sports2 "longmen/server/pkg/db/mysql/models/models_sports"
    "longmen/server/pkg/db/redis/cache"
    "longmen/server/pkg/protobuf"
    "strings"
)

func (s *Server) Get55MachList(ctx context.Context, req *protobuf.Get55MachListReq) (*protobuf.Get55MachListResp, error) {
    //return &protobuf.Get55MachListResp{}, nil
    return getEsMachList(req)
    //return getMysqlMatchList(req)
}

// 热门联赛
func (s *Server) Get55HotLeague(ctx context.Context, req *protobuf.Empty) (*protobuf.Get55HotLeagueResp, error) {
    var LeagueData []*db_sports2.LeagueName
    var err error
    LeagueData, err = cache.GetHotLeagueCache()
    if err != nil {
        LeagueData, err = db_sports.HotLeague(global2.Sport())
        if err != nil {
            return nil, err
        }
        cache.SetHotLeagueCache(LeagueData)
    }
    var respData []*protobuf.LeagueName
    for _, v := range LeagueData {
        respData = append(respData, &protobuf.LeagueName{
            LeagueName: v.CompShortZh,
        })
    }
    return &protobuf.Get55HotLeagueResp{LeagueNames: respData}, nil
}

func getMysqlMatchList(req *protobuf.Get55MachListReq) (*protobuf.Get55MachListResp, error) {
    resp := new(protobuf.Get55MachListResp)
    matchs := db_sports.Get55MatchList(global2.Sport(), int(req.GetSportId()), req.GetComp(), int(req.GetMatchState()), int64(req.GetMatchDate()))
    if len(matchs) > 0 {
        var total int32
        var matchIds []int
        var fEsTmpIds []interface{}
        var bEsTmpIds []interface{}
        var footScoresMap map[int]*mergeFootScore
        var basketScoresMap map[int]*mergeBasketScore
        for _, v := range matchs {
            if v.MatchStatus == 1 {
                matchIds = append(matchIds, v.MatchId)
                if v.SportId == db_sports.BasketBallSportId { //篮球
                    bEsTmpIds = append(bEsTmpIds, v.MatchId)
                } else if v.SportId == db_sports.FootBallSportId { //足球
                    fEsTmpIds = append(fEsTmpIds, v.MatchId)
                }

            }
        }
        var lives []*protobuf.LiveInfo
        if len(matchIds) > 0 {
            lives, _ = db_live.GetLivePbParamForIds(matchIds)
            if len(fEsTmpIds) > 0 {
                footScores := db_sports.EsFootballScore(fEsTmpIds, len(fEsTmpIds))
                global2.Log.Debugf("footScores:%+v", footScores)
                footScoresMap = mergeFootMatchScore(footScores)
            }
            if len(bEsTmpIds) > 0 {
                basketScores := db_sports.EsBasketballScore(bEsTmpIds, len(bEsTmpIds))
                basketScoresMap = mergeBasketMatchScore(basketScores)
            }

        }
        for _, v := range matchs {
            var anchorIds string
            if v.MatchStatus == 1 {
                for _, l := range lives {
                    if v.MatchId == int(l.Matchid) {
                        anchorIds += fmt.Sprintf("%s,", cast.ToString(l.Anchorid))
                    }
                }
                if len(anchorIds) > 0 {
                    anchorIds = strings.TrimRight(anchorIds, ",")
                }
            }
            matchesSuggest := &protobuf.Matches55Suggest{
                Away:              v.Away,
                AwayScore:         v.AwayScore,
                AwayLog:           v.AwayLogo,
                Comp:              v.Comp,
                Home:              v.Home,
                HomeScore:         v.HomeScore,
                HomeLog:           v.HomeLogo,
                CompLog:           v.CompLogo,
                MatchDetailStatus: v.MatchDetailStatus,
                MatchTime:         v.MatchTime,
                TimePlayerd:       v.TimePlayed,
                AnchorIds:         anchorIds,
                SportId:           uint32(v.SportId),
                MatchId:           uint32(v.MatchId),
                RawMatchStatus:    int32(v.RawMatchStatus),
                CompShortZh:       v.CompShortZh,
            }
            if v.SportId == db_sports.FootBallSportId {
                if _, ok := footScoresMap[v.MatchId]; ok {
                    matchesSuggest.FHomeScore = footScoresMap[v.MatchId].Home
                    matchesSuggest.FAwayScore = footScoresMap[v.MatchId].Away
                }

            } else if v.SportId == db_sports.BasketBallSportId {
                if _, ok := basketScoresMap[v.MatchId]; ok {
                    matchesSuggest.BHomeScore = basketScoresMap[v.MatchId].Home
                    matchesSuggest.BAwayScore = basketScoresMap[v.MatchId].Away
                }
            }
            if v.MatchStatus == db_sports.MatchStaring {
                resp.Staring = append(resp.Staring, matchesSuggest)
                total++
            }
            if v.MatchStatus == db_sports.MatchPending {
                resp.Pending = append(resp.Pending, matchesSuggest)
                total++
            }
            if v.MatchStatus == db_sports.MatchFinished {
                resp.Finished = append(resp.Finished, matchesSuggest)
                total++
            }
        }
        resp.Total = total
    }
    return resp, nil
}

func mergeFootMatchScore(sourceMatchScore []*db_sports2.FootballScores) map[int]*mergeFootScore {
    var resp map[int]*mergeFootScore
    resp = make(map[int]*mergeFootScore)
    for _, v := range sourceMatchScore {
        resp[v.Id] = &mergeFootScore{
            Home: &protobuf.FootScore{
                Score:        int32(v.HomeScore.Score),
                HalfScore:    int32(v.HomeScore.HalfScore),
                RedCard:      int32(v.HomeScore.RedCard),
                YellowCard:   int32(v.HomeScore.YellowCard),
                CornerKick:   int32(v.HomeScore.CornerKick),
                OtScore:      int32(v.HomeScore.OTScore),
                PenaltyScore: int32(v.HomeScore.PenaltyScore),
            },
            Away: &protobuf.FootScore{
                Score:        int32(v.AwayScore.Score),
                HalfScore:    int32(v.AwayScore.HalfScore),
                RedCard:      int32(v.AwayScore.RedCard),
                YellowCard:   int32(v.AwayScore.YellowCard),
                CornerKick:   int32(v.AwayScore.CornerKick),
                OtScore:      int32(v.AwayScore.OTScore),
                PenaltyScore: int32(v.AwayScore.PenaltyScore),
            },
        }
    }
    return resp
}

func mergeBasketMatchScore(sourceMatchScore []*db_sports2.BasketballScore) map[int]*mergeBasketScore {
    var resp map[int]*mergeBasketScore
    resp = make(map[int]*mergeBasketScore)
    for _, v := range sourceMatchScore {
        home32slice, _ := util.SliceIntToInt32(v.HomeScore)
        away32slice, _ := util.SliceIntToInt32(v.AwayScore)
        resp[v.MatchId] = &mergeBasketScore{
            Home: home32slice,
            Away: away32slice,
        }
    }
    return resp
}

type mergeFootScore struct {
    Home *protobuf.FootScore
    Away *protobuf.FootScore
}

type mergeBasketScore struct {
    Home []int32
    Away []int32
}
